package main

import (
	"net/http"
	"fmt"
	"html/template"
)

type Person struct {
	Name  string
	Title string
	Age   string
}

var myTemplate *template.Template

func userInfo(w http.ResponseWriter, r *http.Request) {
	var arr []Person
	p := Person{Name: "Mary1", Age: "31", Title: "my website"}
	p2 := Person{Name: "Mary2", Age: "32", Title: "my website"}
	p3 := Person{Name: "Mary3", Age: "32", Title: "my website"}
	arr = append(arr, p)
	arr = append(arr, p2)
	arr = append(arr, p3)
	//写到浏览器
	err := myTemplate.Execute(w, arr)
	if err != nil {
		fmt.Println(err)
	}
	//写入文件
	/*file, err := os.OpenFile("d:/test.log", os.O_CREATE|os.O_WRONLY, 0755)
	if err != nil {
		fmt.Println("open file err:", err)
		return
	}
	defer file.Close()
	myTemplate.Execute(file, p)*/
}

func initTemplate(filename string) (err error) {
	myTemplate, err = template.ParseFiles(filename)
	if err != nil {
		fmt.Println("parse file err:", err)
		return
	}
	return
}

func main() {
	initTemplate("/home/simon/golang/src/golang/oldboy/day10/template_http/index.html")
	http.HandleFunc("/user/info", userInfo)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("http listen failed")
	}
}
